package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IArticleService;
import com.example.forum.services.IBoardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: liuli
 * Date: 2024-08-13
 * Time: 20:13
 */
@Slf4j
@RestController
@RequestMapping("/article")
@Api(tags = "文章接口")
public class ArticleController {

    @Resource
    private IArticleService articleService;

    @Resource
    private IBoardService boardService;

    /**
     * 发布新帖子
     * @param boardId 版块id
     * @param title 标题
     * @param content 文章内容
     * @return
     */
    @ApiOperation("发布新帖")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("版块id") @RequestParam("boardId") @NonNull Long boardId,
                            @ApiParam("标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("文章内容") @RequestParam("content") @NonNull String content){

        //检验用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1){
            //用户已禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //版块校验
        Board board =  boardService.selectById(boardId.longValue());
        if(board == null || board.getDeleteState() == 1 || board.getState() == 1){
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }

        //封装文章对象
        Article article = new Article();
        article.setTitle(title);      //标题
        article.setContent(content);  //正文
        article.setBoardId(boardId);   //版块id
        article.setUserId(user.getId());  //作者id

        //调用service
        articleService.create(article);
        //响应成功
        return AppResult.success();
    }

    @ApiOperation("获取帖子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@ApiParam("版块id") @RequestParam(value = "boardId",required = false) Long boardId){

        // 定义返回的集对象
        List<Article> result;
        // 根据传的参数返回不同板块的帖⼦列表
        if (boardId == null) {
            // 参数为空时表⽰⾸⻚帖⼦列表
            result = articleService.selectAll();
            log.info("查询所有帖⼦列表");
        } else {
            // 参数i 为空时表⽰指定版本的帖⼦列表
            result = articleService.selectAllByBoardId(boardId);
            log.info("查询版块帖⼦列表, boardId = " + boardId);
        }
        // 如果为null返回⼀个空JSON
        if (result == null) {
            result = new ArrayList<>();
        }
        // 返回结果
        return AppResult.success(result);
    }

    @ApiOperation("根据帖子id获取详情")
    @GetMapping("/details")
    public AppResult<Article> getDetails(HttpServletRequest request,
            @ApiParam("帖子Id") @RequestParam("id") @NonNull Long id){
        //从session中获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);


       //调用Service,获取帖子详情
        Article article = articleService.selectDetailById(id);
        //判断是否为空
        if(article == null){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断用户是否为作者
        if(user.getId() == article.getUserId()){
            //标识为作者
            article.setOwn(true);
        }

        //返回成功
        return  AppResult.success(article);
    }


    @ApiOperation("编辑帖⼦")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam(value = "帖子Id") @RequestParam(value = "id") @NonNull Long id,
                            @ApiParam(value = "文章标题") @RequestParam(value = "title") @NonNull String title,
                            @ApiParam(value = "帖子内容") @RequestParam(value = "content") @NonNull String content) {
        // 获取⽤户信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 判断是否被禁⾔
        if (user.getState() == 1) {
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        // 获取帖⼦详情
        Article article = articleService.selectById(id);
        // 数据校验
        if (article == null) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 判断发帖⼈是不是当前⽤户
        if (article.getUserId() != user.getId()) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        // 判断帖⼦状态是否异常
        if (article.getState() == 1 || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        // 调用service
        articleService.modify(id, title, content);
        // 打印日志
        log.info("帖⼦修改成功. Article id = " + id + "User id = " +  user.getId() + ".");
        // 返回结果
        return AppResult.success();
    }


   /**
    * 点赞
    * @param id 帖子Id
    * @return AppResult
   */
   @ApiOperation("点赞")
   @PostMapping("/thumbsUp")
   public AppResult thumbsUp(HttpServletRequest request,
                          @ApiParam(value = "帖⼦Id") @RequestParam(value = "id")
                          @NonNull Long id) {
       // 获取⽤户信息
       HttpSession session = request.getSession();
       User user = (User) session.getAttribute(AppConfig.USER_SESSION);
       // 判断是否被禁⾔
       if (user.getState() != 0) {
           // 打印日志
           log.warn(ResultCode.FAILED_USER_BANNED.toString() + ", userId = " + user.getId());
           // 返回错误信息
           return AppResult.failed(ResultCode.FAILED_USER_BANNED);
       }
       // 更新点赞数
       articleService.thumbsUpById(id);
       // 返回结果
       return AppResult.success();
   }

    /**
     * 根据Id删除帖⼦
     * @param id 帖⼦Id
     * @return
     */
    @ApiOperation("删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById (HttpServletRequest request,
                                 @ApiParam("帖⼦Id") @RequestParam("id") @NonNull Long id) {
        // 1. ⽤户是否禁⾔
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 查询帖⼦信息
        Article article = articleService.selectById(id);
        // 2. 帖⼦是否存在或已删除
        if (article == null || article.getDeleteState() == 1) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 3. ⽤户是否是作者
        if (article.getUserId() != user.getId()) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        // 调⽤Service执行删除
        articleService.deleteById(id);
        // 返回成功
        return AppResult.success();
    }



    @ApiOperation("获取用户的帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                                    @ApiParam("用户Id") @RequestParam(value = "userId",required = false) Long userId){
        //如果userId为空，从session中获取当前登录的用户Id
        if(userId == null) {
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        //调用service
        List<Article> articles = articleService.selectByUserId(userId);
        return  AppResult.success(articles);
    }



}
